﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DDD4Fun.Common
{
    public class CFormat
    {
        public static void getPerson(string format)
        {
            CFormatPerson p = new CFormatPerson() { IDCode = Guid.NewGuid().ToString(), LastName = "lee", FirstName = "jimmy" };
            Console.WriteLine(p.ToString(format, null));

            PersonFomatter fommater = new PersonFomatter();
            Console.WriteLine(fommater.Format(format, p, null));

            Console.WriteLine(p.ToString(format, (PersonFomatter)fommater.GetFormat(fommater.GetType())));
            Console.WriteLine(p.ToString(format, fommater));
        }
    }

    class CFormatPerson : IFormattable
    {
        public string IDCode { set; get; }

        public string FirstName { set; get; }

        public string LastName { set; get; }

        #region IFormattable Members

        public string ToString(string format, IFormatProvider formatProvider)
        {
            switch (format)
            {
                case "ch":
                    return this.ToString();
                case "eg":
                    return string.Format("{0} {1}",FirstName,LastName);
                default:
                    //return this.ToString();
                    ICustomFormatter formatter = formatProvider as ICustomFormatter;
                    if (formatter == null) return this.ToString();

                    return formatter.Format(format, this, null);
            }
        }

        #endregion

        public override string ToString()
        {
            return string.Format("{0} {1}", LastName, FirstName);
        }
    }

    class PersonFomatter:IFormatProvider,ICustomFormatter
    {
        #region IFormatProvider Members

        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
                return this;

            return null;
        }

        #endregion

        #region ICustomFormatter Members

        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            CFormatPerson p = arg as CFormatPerson;
            if (p == null)
                return "";

            switch (format)
            {
                case "ch":
                    return p.ToString();
                case "eg":
                    return string.Format("{0} {1}", p.FirstName, p.LastName);
                default:
                    return p.ToString();
            }
        }

        #endregion
    }
}
